package org.yylnb.openplatform.websocket.handler;


import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author RainLin
 * @date 2020/7/28 - 21:00
 */
@Component
public class MyTextWebSocketHandler extends TextWebSocketHandler {
    private static Map<String, WebSocketSession> allClients = new ConcurrentHashMap<>();

    /**
     * 建立链接后的回调
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //保存会话数据,因为你不保存以后就拿不到了,拿不到就没用了, 数据都必须要保存才有意义
        Object name = session.getAttributes().get("name");
        allClients.put((String) name,session);
    }


    /**
     *
     * @param session 发送者的会话对象
     * @param message 发送者发送的内容
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String neirong = message.getPayload();
        //获取发送的内容

        //解析发送的内容,把内容中接受者的信息获取出来

        //根据接受者的信息找到接受者的链接对象

        //通过链接对象把数据发过去
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object name = session.getAttributes().get("name");
        allClients.remove(name);
    }

    public static Map<String, WebSocketSession> getAllClients() {
        return allClients;
    }


}
